﻿using Newtonsoft.Json;
using System;
using System.Linq;
using System.Web.Mvc;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.SocketEnum;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.WebProvider;
using ZBJF.Warranty.WeiXin;
using ZBJF.Warranty.Common.Enums.InsuranceWarranty;
using ZBJF.Warranty.Model.ViewModel.SocketModel;
using ZBJF.Warranty.Model.ViewModel.Udesk;
using System.Collections.Generic;


namespace ZBJF.Warranty.CustomerService.Controllers
{
    public class UdeskController : BaseController
    {
        //
        // GET: /Udesk/
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Index(CustomerInfoModel model)
        {
            var total = 0;
            var list = (from a in ServiceFactory.Udesk_CustomerInfoServiceInstance.GetPagingList(model, out total)
                join b in ServiceFactory.Udesk_CustomerServiceInfoServiceInstance.LoadEntities(n => true) on a.Owner_id
                    equals b.UdeskID into temp
                from c in temp.DefaultIfEmpty()
                select new
                {
                 a.UdeskID,
                 a.Email,
                 a.Cellphones,
                 a.Nick_name,
                 a.Source_channel,
                 ServiceName=c.Nick_name
                }).ToList();
            
         
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }       
        #region 获取聊天记录 + ActionResult GetChatRecord()
        /// <summary>
        /// 获取聊天记录
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        public ActionResult GetChatRecord(CustomerInfoModel param,ChatDetailModel model)
        {
            int total = 0,total1=0;
            model.iDisplayLength = int.MaxValue;
            var data = (from a in ServiceFactory.Udesk_CustomerInfoServiceInstance.GetPagingList(param, out total)
                        join b in ServiceFactory.Udesk_ChatRecordServiceInstance.LoadEntities(n => true) on a.UdeskID equals b.customer_id
                into temp from c in temp.DefaultIfEmpty()
                        join d in ServiceFactory.Udesk_ChatDetailServiceInstance.GetPagingList(model, out total1) on c.sub_session_id equals d.sub_session_id
                into temp1 from f in temp1.DefaultIfEmpty()
                join j in ServiceFactory.Udesk_CustomerServiceInfoServiceInstance.LoadEntities(n=>true) on a.Owner_id equals j.UdeskID
                into temp2 from h in temp2.DefaultIfEmpty()
                        select new
                        {
                          ID = f == null?0:f.ID,
                          content = f == null ?"": f.content,
                          contentType = f == null ?"": f.contentType,
                          sender=f==null?0:f.sender,
                          created_at=f==null?DateTime.MinValue:f.created_at,
                          Aliase=h==null?"":h.Aliase,
                          a.Nick_name  
                        }).ToList().OrderBy(a=>a.created_at);
            return Json(new
            {
                sEcho = param.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = data
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion
        #region 获取用户关联的报案单号列表 + ActionResult GetUserOrderList(long customer_id)
        [HttpGet]
        public ActionResult GetUserOrderList(long customer_id)
        {
            if (customer_id<=0)
                return Json(new ResultModel(false, "参数错误！", CodeStateEnum.Failed), JsonRequestBehavior.AllowGet);
            var result =
                (from a in
                    ServiceFactory.Udesk_CustomerInfoOrderServiceInstance.LoadEntities(t => t.customer_id.Equals(customer_id))
                    join b in ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadEntities(n => true) on
                    a.WarrantyRecordId equals b.ID into temp
                    from c in temp.DefaultIfEmpty()
                    select new
                    {
                      WarrantyRecordNo=c.WarrantyRecordNo
                    }).ToList();
            return Json(new ResultModel(true, "获取成功。", CodeStateEnum.Success, result), JsonRequestBehavior.AllowGet);
        }
        #endregion
        #region 关联报案单号 + ActionResult AssociatedWarrantyRecordNo(WeiXinUserInsuranceOrderParam param)
        /// <summary>
        /// 关联报案单号
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult AssociatedWarrantyRecordNo(CustomerInfoOrderModel param)
        {
            if (param == null || !param.customer_id.HasValue || string.IsNullOrEmpty(param.WarrantyRecordNo))
            {
                return Json(new ResultModel(false, "参数错误！", CodeStateEnum.Failed), JsonRequestBehavior.AllowGet);
            }
            //查询报案单号
            InsuranceWarrantyRecord order = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadEntities(t => t.WarrantyRecordNo == param.WarrantyRecordNo).FirstOrDefault();
            if (order == null)
                return Json(new ResultModel(false, "报案单号不存在！", CodeStateEnum.Failed), JsonRequestBehavior.AllowGet);

            Udesk_CustomerInfoOrder orderRela = ServiceFactory.Udesk_CustomerInfoOrderServiceInstance.LoadEntities(t => t.customer_id.Equals(param.customer_id.Value) && t.WarrantyRecordId == order.ID).FirstOrDefault();
            if (orderRela != null)
            {
                return Json(new ResultModel(false, "已存在关联信息！", CodeStateEnum.Failed), JsonRequestBehavior.AllowGet);
            }

            long id = ServiceFactory.Udesk_CustomerInfoOrderServiceInstance.AddEntities(new Udesk_CustomerInfoOrder { WarrantyRecordId = order.ID, customer_id = param.customer_id.Value, CreateTime = DateTime.Now }).ID;

            if (id < 1)
                return Json(new ResultModel(false, "关联失败！", CodeStateEnum.Failed), JsonRequestBehavior.AllowGet);

            return Json(new ResultModel(true, "关联成功", CodeStateEnum.Success), JsonRequestBehavior.AllowGet);
        }
        #endregion
        #region 获取用户的报案单号 + ActionResult GetUserReportNumber(long openId)
        public ActionResult GetUserReportNumber(long customer_id)
        {
            if (customer_id <= 0)
                return Json(new ResultModel(false, "参数错误", CodeStateEnum.Failed), JsonRequestBehavior.AllowGet);
            List<Byte> list = ServiceFactory.InsuranceWarrantyRecordServiceInstance.GetStatusList(InsuranceWarrantyRecordTaskType.ToBeProcess);
            var data = (from a in ServiceFactory.Udesk_CustomerInfoOrderServiceInstance.LoadEntities(o => o.customer_id == customer_id)
                           join b in ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadEntities(n=>list.Contains(n.Status)) on a.WarrantyRecordId equals b.ID
                           into temp from c in temp.DefaultIfEmpty()
                           select new
                           {
                             WarrantyRecordNo =c==null?"": c.WarrantyRecordNo,
                             CreateTime = c == null ? DateTime.MinValue : c.CreateTime,
                             ID = c == null ? 0 : c.ID, 
                            }).ToList();
            return Json(new ResultModel(true, "获取成功", CodeStateEnum.Success, data), JsonRequestBehavior.AllowGet);
        }
        #endregion
        #region 收集资料 + ActionResult CollectData(CollectOrderDataModel model)
        [HttpPost]
        public ActionResult CollectData(CollectOrderDataModel model)
        {
            if (model == null ||
                model.ID < 1 ||
                model.udeskID<1 ||
                string.IsNullOrEmpty(model.WarrantyRecordNo) ||
                string.IsNullOrEmpty(model.FileinfoType) ||
                model.ImagesUrl == null ||
                model.ImagesUrl.Count() < 1
                )
                return Json(new ResultModel(false, "参数错误", CodeStateEnum.Failed));

            EnumHelper enumHelper = EnumHelper.Instance;
            string imageTypeName = enumHelper.GetDescription(typeof(WarrantyRecordImageEnums), model.FileinfoType);

            InsuranceWarrantyRecord entityRecord = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(model.ID);
            //1、把图片移动到别的文件夹——下载已处理任务的时候需要压缩图片，下载文件（保存路径与/InsuranceWarrantyRecordController/SaveIWRImages下的一致）
            string folderName = string.Format("/UploadFile/File/workOrder/{0}/{1}/{2}/{3}_{4}_{5}/{6}/", entityRecord.CreateTime.Year, entityRecord.CreateTime.Month, entityRecord.CreateTime.Day, entityRecord.Reporter, entityRecord.ReporterPhone.Trim(), entityRecord.WarrantyRecordNo, imageTypeName);

            string message = "";
            var entity = new InsuranceWarrantyRecordImages { InsuranceWarrantyRecordId = model.ID };
            for (int i = 0; i < model.ImagesUrl.Count(); i++)
            {
                var iwrImage = model.ImagesUrl[i];
                string fileName = System.Guid.NewGuid().ToString() + ".png";
                bool isOk = FileHelper.MoveFile(System.Web.HttpContext.Current.Server.MapPath(iwrImage), System.Web.HttpContext.Current.Server.MapPath(folderName), fileName);
                if (iwrImage != null && isOk)
                {
                    //新增素材
                    entity.FileName = fileName;
                    entity.FilePath = folderName + fileName;
                    entity.FileSize = "0";
                    entity.IsAvailable = true;
                    entity.CreateBy = CurrentUser.UserAccount;
                    entity.CreateTime = DateTime.Now;
                    entity.ImageType = Convert.ToByte(model.FileinfoType); //资料类型
                    ServiceFactory.InsuranceWarrantyRecordImagesServiceInstance.AddEntities(entity);
                    long ChatDetailID = model.ChatDetailID[i];
                    //修改聊天记录的地址
                    Udesk_ChatDetail ud = ServiceFactory.Udesk_ChatDetailServiceInstance.LoadEntities(o => o.ID == ChatDetailID).FirstOrDefault();
                    ud.content= folderName + fileName;
                    ServiceFactory.Udesk_ChatDetailServiceInstance.UpdateEntities(ud);
                }
                else
                {
                    message += "关联出错：" + iwrImage + "；\r\n";
                }
            }

            if (string.IsNullOrEmpty(message))
                return Json(new ResultModel(true, "关联成功", CodeStateEnum.Success));
            else
                return Json(new ResultModel(false, message, CodeStateEnum.Failed));
        }
        #endregion

        public ActionResult CallRecord()
        {
            return View();
        }
        [HttpPost]
        public JsonResult CallRecord(CallRecordModel model)
        {
            var total = 0;
            var list =ServiceFactory.Udesk_CallRecordServiceInstance.GetPagingList(model, out total).Select(o => new
                      {
                      o.ID,
                      o.Call_start_at,
                      o.Call_type,
                      o.Call_result,
                      o.User_name,
                      o.Call_source,
                      o.Satisfaction,
                      o.Queue_type,
                      o.Device_info,
                      o.Record_url,
                      o.Agent_nick_name
                      }).ToList();
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult CallRecordDetails(int ID)
        {
            var order = ServiceFactory.Udesk_CallRecordServiceInstance.LoadByID(ID);
            return View(order);
        }
    }
}